package com.cppstudio.movie.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.cppstudio.movie.activity.R;
import com.cppstudio.movie.adapter.ImageAdapter;
import com.cppstudio.movie.model.Movie;
import com.cppstudio.movie.widget.util.ActionBarTool;



import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class FilmFragment extends Fragment implements OnItemSelectedListener,OnItemClickListener{
     private ImageAdapter adapter;
     private Gallery mGallery;
	 private TextView title;
	 private TextView score;
	 private RatingBar rating;
     private int showingIndex = -1;   
     private int toShowIndex = 0;  
     private List<Movie> list=new ArrayList<Movie>();
     
     private Handler handler = new Handler() {
  		public void handleMessage(Message msg) {
  			
  			final List<Movie> result = (List<Movie>) msg.obj;
 			list.addAll(result);
 			adapter.notifyDataSetChanged();
 			
 			
 		   
  		};
  	};
     
     @Override  
	    public void onActivityCreated(Bundle savedInstanceState) {  
	        // TODO Auto-generated method stub  
	        super.onActivityCreated(savedInstanceState);  
	       Thread t=new Thread(run);
	       t.start();
	      
	 }  
	  
	    @Override  
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
	            Bundle savedInstanceState) {  
	       
	       View view=inflater.inflate(R.layout.fragment_film, container, false);
	       mGallery=(Gallery)view.findViewById(R.id.film_gallery);
	       title=(TextView)view.findViewById(R.id.film_name);
	       rating=(RatingBar)view.findViewById(R.id.film_rating);
	       score=(TextView)view.findViewById(R.id.film_score);
	       adapter=new ImageAdapter(this.getActivity(),list);
	       mGallery.setAdapter(adapter);
	       mGallery.setSpacing(5);
	    //   mGallery.setSelection(adapter.getCount()/2);
	       mGallery.setOnItemSelectedListener(this);
	       mGallery.setOnItemClickListener(this);
	       return view;  
	    }

		@Override
		public void onItemSelected(AdapterView<?> arg0, View view, int position,
				long arg3) {
			// TODO Auto-generated method stub
			 toShowIndex=position;
			String strScore= list.get(position).getScore();
		    float num= Float.parseFloat( list.get(position).getScore().substring(0, list.get(toShowIndex).getScore().length()-1));
		    Log.v("B2B",""+num);
		    score.setText(strScore);
			rating.setRating(num);
			
		   /*
			rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){
				       
	 				@Override
	 				public void onRatingChanged(RatingBar ratingBar, float rating,
	 						boolean fromUser) {
	 					// TODO Auto-generated method stub
	 					    Log.v("B B",""+num);
	 					    ratingBar.setRating(num);
	 					   
	 				}
	 		    	   
	 		       });
		      */
			final Handler handler=new Handler(){
				@Override
				public void handleMessage(Message msg){
					title.setText(list.get(toShowIndex).getTitle());
					if(showingIndex!=toShowIndex){
						showingIndex=toShowIndex;
						adapter.setSelectItem(toShowIndex);
					}
					
				}
			};
			
			Thread checkChange=new Thread(){
				@Override
				public void run(){
					
					int myIndex=toShowIndex;
					try{
						
						sleep(100);
						if(myIndex==toShowIndex){
							handler.sendEmptyMessage(0);
						}
					}catch(InterruptedException e){
						e.printStackTrace();
					}
				}
			};
		      checkChange.start();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			// TODO Auto-generated method stub
			Log.v("VIEW",""+position%6);
		}
		
		Runnable run=new Runnable(){
			    
				@Override
				public void run() {
					// TODO Auto-generated method stub
					
					Message msg = handler.obtainMessage();
					msg.obj =getJson();
					handler.sendMessage(msg);
					
					
				}
		    	
		    };
		   private List<Movie> getJson(){
		    	 List<Movie> list=new  ArrayList<Movie>();
		    	HttpClient client = new DefaultHttpClient();
		        HttpGet myget = new HttpGet("http://192.168.1.133/json.php");
		        try {
		            HttpResponse response = client.execute(myget);
		            String result = EntityUtils.toString(response.getEntity(),"GBK");  
		            JSONArray jsonArray=new JSONArray(result);
		            for(int i=0;i<jsonArray.length();i++){
		            	JSONObject jo=jsonArray.getJSONObject(i);
		            	final Movie item=new Movie();
		            	item.setScore(jo.getString("score"));
			    		item.setTitle(jo.getString("name"));
			    		item.setUrl(jo.getString("image"));
			    	//	for(int j=0;j<10;j++)
			    		  list.add(item);
		            }
		           
		        } catch (Exception e) {
		            Log.v("url response", "false");
		            e.printStackTrace();
		        }
		        return list;
		        }
}
